package com.huike.aspect;

import com.alibaba.fastjson.JSONObject;
import com.huike.entity.SysOperLog;
import com.huike.mapper.SysOperLogMapper;
import com.huike.mapper.SysUserMapper;
import com.huike.utils.BaseContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Data
@Component
@Slf4j
public class OperLogAspect {

    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private SysOperLogMapper sysOperLogMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Around("@annotation(com.huike.aspect.OperationAnnotation)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        //操作人名称
        // String userName = sysUserMapper.selectById(BaseContext.getCurrentId()).getUserName();
        String userName = "admin";
        //请求方式
        String method = httpServletRequest.getMethod();
        log.info("请求方式"+method);
        //请求路径
        String requestURI = httpServletRequest.getRequestURI();
        log.info("请求路径"+requestURI);
        //模块名称
        String titleName="用户管理";
        //ip
        String remoteAddr = httpServletRequest.getRemoteAddr();


        SysOperLog sysOperLog = new SysOperLog();

        sysOperLog.setOperIp(remoteAddr);
        sysOperLog.setOperName(userName);
        sysOperLog.setOperTime(new Date());
        sysOperLog.setOperUrl(requestURI);
        sysOperLog.setTitleName(titleName);
        sysOperLog.setRequestMethod(method);

        //计算耗时,外加方法执行
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();

        //日志写入
        sysOperLogMapper.insert(sysOperLog);
        return result;
    }
}
